﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using LuckyBingoRcon.Commands.Events;

namespace LuckyBingoRcon.Commands
{
    public class PlaylistCommand : Command
    {
		public EventHandler<PlaylistCommandEventArgs> OnResponse;

        public PlaylistCommand(bool setValue)
        {
            if(!setValue)
                base.commandText = "playlist ";
            else
                // Thought this would solve our get / set problem, but the server doesn't like having the current gametype omitted
                //base.commandText = "setadmindvar playlist_excludeGametype ";
                base.commandText = "setadmindvar playlist ";
            base.args = null;
        }

		protected override void CommandOnResponse(string response)
		{

			int playlist = -1;
			StringReader sr = new StringReader(response);

			try
			{
				while (sr.Peek() > 0)
				{
					string ln = sr.ReadLine().Trim();
					if (!String.IsNullOrEmpty(ln) && (ln.StartsWith("\"playlist") || ln.StartsWith("playlist")))            // Heli: Play list line has "playlist", not playlist at beginning
					{
						int index = ln.IndexOf("is:");                                          // Heli: Find (if packet was received correctly) the characters before the playlist number
						if (index > 0 && index < ln.Length - 5)
						{
							ln = ln.Remove(0, index + 5);                                       // Remove all characters before the playlist number ...
							index = ln.IndexOf("^7");
							if (index > 0)
								ln = ln.Remove(index);
							ln = ln.Trim();
                            if (base.gametypeLookup.IsValidPlayList(ln))
								int.TryParse(ln, out playlist);
							break;
						}
					}
				}

				if (OnResponse != null)
				{
					PlaylistCommandEventArgs e = new PlaylistCommandEventArgs();
					e.PlayList = playlist;
					OnResponse(this, e);
				}
			}
			catch (Exception error)
			{
				if (OnResponse != null)
				{
					PlaylistCommandEventArgs e = new PlaylistCommandEventArgs();
					e.PlayList = playlist;
					e.Error = error;
					OnResponse(this, e);
				}
			}

			sr.Close();
		}

        public override string ToString()
        {
            if (base.commandText.Contains("setadmindvar"))   // Is a set command
                return "Set\tPlaylist\t=\t" + base.args.ToString();
            else
                return "Get\tPlaylist";
        }
    }
}
